import { createStore } from 'redux';

// 全局数据的初始状态
const initialModel = {
  userList: [],
};

fetch('api/data', {
  method: 'GET',
})
  .then((resp) => resp.json())
  .then((json) => {
    console.log(json);
    initialModel.userList = json.userList;
  });

export default createStore((model = initialModel, action) => {
  const { userList } = model;

  switch (action.type) {
    case 'create_user':
      const { user } = action.payload;
      return {
        userList: [
          ...userList,
          {
            key: String(userList.length + 1),
            ...user,
          },
        ],
      };
    case 'delete_user':
      const { key } = action.payload;
      return {
        userList: userList.filter((user) => {
          return user.key !== key;
        }),
      };

    case 'update_user':
      const { user: updatedUser } = action.payload;
      return {
        userList: userList.map((user) => {
          if (user.key !== updatedUser.key) {
            return user;
          }
          return updatedUser;
        }),
      };
    default:
      return model;
  }
});
